package com.zzw.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzw.bean.Product;
import com.zzw.dao.ProductMapper;
import com.zzw.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public int addProduct(Product product) {
        Date now = new Date();
        product.setCreateTime(now);
        product.setUpdateTime(now);

        // 如果没有商品编码，则生成一个
        if (product.getProductCode() == null || product.getProductCode().isEmpty()) {
            product.setProductCode(generateProductCode());
        }

        // 如果没有设置状态，则默认为启用
        if (product.getStatus() == null) {
            product.setStatus(1);
        }

        return productMapper.insertProduct(product);
    }

    @Override
    public int updateProduct(Product product) {
        product.setUpdateTime(new Date());
        return productMapper.updateProduct(product);
    }

    @Override
    public int deleteProduct(Integer id) {
        return productMapper.deleteProduct(id);
    }

    @Override
    public Product getProductById(Integer id) {
        return productMapper.selectProductById(id);
    }

    @Override
    public Product getProductByCode(String productCode) {
        return productMapper.selectProductByCode(productCode);
    }

    @Override
    public PageInfo<Product> getProductList(Map<String, Object> params, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectProductList(params);
        return new PageInfo<>(products);
    }

    @Override
    public List<Product> getProductByIds(List<Integer> ids) {
        return productMapper.selectProductByIds(ids);
    }

    @Override
    public String generateProductCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String timeMillis = String.valueOf(System.currentTimeMillis()).substring(9);
        return "P" + dateStr + timeMillis;
    }
}
